
package com.baiduspring.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Order(1)
@WebFilter(filterName = "BaiduSpringFilter", urlPatterns = {"/specialcolumn/edit/view", "/specialcolumn/howtowrite","/specialcolumn/modifyview/*","/usercenter/*", "/"})
@Slf4j
public class BaiduSpringFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String userAttr = "user";
        String path = "/";
        if (Objects.isNull(req.getSession().getAttribute(userAttr)) && !path.equalsIgnoreCase(req.getRequestURI())) {
            req.getSession().setAttribute("login_before_skip_uri", req.getRequestURI());
            //不改变请求URL
            req.getRequestDispatcher("/user/join").forward(req, resp);
        } else {
            Object o = req.getSession().getAttribute("login_before_skip_uri");
            if (Objects.nonNull(o)) {
                String login_before_skip_uri = o.toString();
                req.getSession().removeAttribute("login_before_skip_uri");
                //改变请求URL
                resp.sendRedirect(login_before_skip_uri);
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
